﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using HHMMS.WorkFlow.Model;
using HHMMS.WorkFlow.Service;
using HHMMS.WorkFlow;
using System.Transactions;
using Bingosoft.Web.Utils;

namespace HHMMS.UI.Modules.Workflow
{
    public partial class WorkItem : System.Web.UI.Page
    {
        #region 字段属性
        protected WFAPI workflowApi = new WFAPI();

        /// <summary>
        /// 获取当前工作流ID。
        /// </summary>
        protected int WorkflowId { get; private set; }

        /// <summary>
        /// 获取当前环节ID。
        /// </summary>
        protected int ActivityId { get; private set; }

        /// <summary>
        /// 从Url中获取当前实例ID。
        /// </summary>
        protected string InstanceId
        {
            get { return Request.GetQuery<string>("instanceId"); }
        }

        /// <summary>
        /// 从Url中获取当前任务ID。
        /// </summary>
        protected int TaskId
        {
            get { return Request.GetQuery<int>("taskId"); }
        }

        /// <summary>
        /// 从Url中获取当前页面操作类型：0新增流程 1编辑流程 2查看流程
        /// </summary>
        protected int ActionType
        {
            get { return Request.GetQuery<int>("actionType"); }
        }

        /// <summary>
        /// 业务表单。
        /// </summary>
        protected WFUserControl WFFormControl { get; private set; }
        #endregion

        #region 事件处理
        protected void Page_Load(object sender, EventArgs e)
        {
            //1.初始化流程相关信息
            if (this.ActionType == 0)
            {
                this.WorkflowId = Request.GetQuery<int>("workflowId");
                workflowApi.Load(this.WorkflowId);
            }
            else
            {
                workflowApi.Load(this.InstanceId, this.TaskId);
                this.WorkflowId = workflowApi.CurrentWorkflow.WorkflowId.Value;
            }
            this.ActivityId = this.workflowApi.CurrentActivity.ActivityId.Value;
            this.lbAppName.Text = this.Title = string.Format("{0}-{1}", this.workflowApi.CurrentWorkflow.Name, this.workflowApi.CurrentActivity.ActivityName);

            //2.加载流程表单
            if (!string.IsNullOrEmpty(workflowApi.CurrentWorkflow.FormPath))
            {
                this.WFFormControl = Page.LoadControl(workflowApi.CurrentWorkflow.FormPath) as WFUserControl;
                this.WFFormControl.ActionType = this.ActionType;
                this.WFFormControl.CurrentActivity = workflowApi.CurrentActivity;
                this.WFFormControl.CurrentWorkflow = workflowApi.CurrentWorkflow;
                if (this.ActionType > 0)
                {
                    this.WFFormControl.DataKey = workflowApi.CurrentInstance.DataKey;
                    this.WFFormControl.Title = workflowApi.CurrentInstance.InstanceName;
                }
                this.phForm.Controls.Add(this.WFFormControl);
                this.workflowApi.WorkflowExecute += new WorkflowExecuteEventHandler(this.WFFormControl.OnWorkflowExecute);
            }
            
            if (!IsPostBack)
            {
                //3.加载审批选项
                var choices = workflowApi.GetPartChoices();
                if (choices != null)
                {
                    foreach (string choice in workflowApi.GetPartChoices())
                    {
                        this.PartChoice.Items.Add(choice);
                    }
                }
                this.PartChoice.Items.Insert(0, new ListItem("-请选择-", ""));
                if (workflowApi.CurrentWorkItem != null)
                {
                    this.PartChoice.SelectedValue = workflowApi.CurrentWorkItem.PartChoice;
                    this.PartComment.Text = workflowApi.CurrentWorkItem.PartComment;
                }

                //4.加载审批历史
                this.gridApprovalHistory.DataBind();
            }
        }

        protected void ToolBarClick(object sender, CommandEventArgs e)
        {
            LinkButton link = sender as LinkButton;
            switch (link.Attributes["key"])
            {
                case "Save":
                    if (this.Save())
                    {
                        var url = string.Format("WorkItem.aspx?instanceId={0}&taskId={1}&actionType=1", workflowApi.CurrentInstance.InstanceId, 1);
                        if (this.ActionType > 0)
                        {
                            url = Request.Url.PathAndQuery;
                        }
                        this.MessageBox("保存成功！", false, true, url);
                    }
                    break;
                case "Send":
                    if (this.Send())
                    {
                        this.MessageBox("提交成功！", true, true);
                    }
                    break;
                case "Discard":
                    if (this.Discard())
                    {
                        this.MessageBox("作废成功！", true, true);
                    }
                    break;
                case "Close":
                    break;
                default: break;
            }
        }
        #endregion

        #region 相关方法
        private bool Save()
        {
            using (TransactionScope tran = new TransactionScope(TransactionScopeOption.Required))
            {
                if (this.WFFormControl.SaveData())
                {
                    this.workflowApi.Save(this.WFFormControl.Title, this.WFFormControl.DataKey, this.PartChoice.SelectedValue, this.PartComment.Text);
                }
                tran.Complete();
            }
            return true;
        }

        private bool Send()
        {
            using (TransactionScope tran = new TransactionScope(TransactionScopeOption.Required))
            {
                if (this.WFFormControl.SaveData())
                {
                    if (this.ActionType == 0)
                    {
                        this.workflowApi.Save(this.WFFormControl.Title, this.WFFormControl.DataKey, this.PartChoice.SelectedValue, this.PartComment.Text);
                    }
                    this.workflowApi.Run(this.PartIds.Value, this.PartChoice.SelectedValue, this.PartComment.Text);
                }
                tran.Complete();
            }
            return true;
        }

        private bool Discard()
        {
            using (TransactionScope tran = new TransactionScope(TransactionScopeOption.Required))
            {
                this.workflowApi.Discard(this.PartComment.Text);
                tran.Complete();
            }
            return true;
        }
        #endregion
    }
}